/**
 * 
 */
package info.niwota.webshot;

import java.io.File;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public final class Utils {
	private static final String SEARCH_DEFAULT = "http://www.google.com/search?q=";
	private static final String INSTALL_PASTA_PKG = "market://search?q=pname:info.niwota.pasta";

	private static final int NAME_MAX_LEN = 32;

	/**
	 * 
	 */
	private Utils() {
	}

	public static String parseUrlFromClipboard(Context ctx) {
		//find the first url if any
		ClipboardManager cb = (ClipboardManager) ctx
				.getSystemService(Context.CLIPBOARD_SERVICE);
		boolean has = cb.hasText();
		if (!has) {
			return null;
		}
		String txt = cb.getText().toString();
		final String regex = "[\\s]+";
		String[] sa = txt.split(regex);
		int len = sa.length;
		for (int i = 0; i < len; i++) {
			String s = sa[i];
			if (s.startsWith("http://") || s.startsWith("https://")) {
				return s;
			}
		}
		return null;
	}

	/**
	 * 1. replace lf/cr with space 
	 * 2. trim leading/trailing spaces
	 * 
	 * @param s
	 * @return
	 */
	private static String normalize(String s) {
		if (s == null) {
			return "";
		}
		final String regex = "[\\s]+";
		return s.replaceAll(regex, " ").trim();
	}


	/**
	 * remove anything after the last dot (.jpg) or dash (- Google Search)
	 * replace lf/cr with "-"
	 * trim leading/trailing spaces
	 * truncate if longer than 32
	 * 
	 * @param s
	 * @return
	 */
	private static String normalizeName(String n) {
		if (n == null) {
			return null;
		}
		int idx = n.lastIndexOf(".");
		n = (idx > 0 ? n.substring(0, idx) : n);
		idx = n.lastIndexOf("-");
		n = (idx > 0 ? n.substring(0, idx) : n);
		//
		n = n.trim();
		final String regex = "[\\s]+";
		n = n.replaceAll(regex, "-");
		n = truncate(n, NAME_MAX_LEN);
		return n;
	}

	public static String toUri(String input) {
		// check if the input is a valid url,
		// otherwise return a default search url
		if (TextUtils.isEmpty(input)) {
			return SEARCH_DEFAULT;
		}
		String s = normalize(input);
		try {
			final String http = "http://";
			final String https = "https://";
			if (s.startsWith(http) || s.startsWith(https)) {
				URL url = new URL(s);
				return url.toString();
			}
			//crude check
			String u = http + s; //a url without scheme?
			URL url = new URL(u);
			String h = url.getHost();
			final String regex = "[\\s]+";
			//one dot and no spaces
			if (h.indexOf(".") > 0 && h.split(regex).length == 1) {
					return url.toString();
			}
		} catch (Exception e) {
		}
		return SEARCH_DEFAULT + URLEncoder.encode(s);
	}

	public static Intent toShareIntent(String subject, String body, Uri uri) {
		Intent i = new Intent();
		i.setAction(Intent.ACTION_SEND);
		String type = "image/*";
		i.setType(type);
		//
		// i.setType("message/rfc822"); //only show email
		// i.setType("text/plain"); //emulator
		// i.setType("message/rfc822"); //phone
		//
		// String subject = getString(R.string.msg_subject_default);
		// String body = getString(R.string.msg_body_default);

		// String subject = Preferences.getSubject(this);
		// String body = Preferences.getBody(this);

		// email
		// String[] emails = Preferences.getEmails(this);
		// if (emails != null) {
		// i.putExtra(Intent.EXTRA_EMAIL, emails);
		// }
		//
		i.putExtra(Intent.EXTRA_SUBJECT, subject);
		i.putExtra(Intent.EXTRA_TEXT, body);

		//
		i.putExtra(Intent.EXTRA_STREAM, uri);
		//
		// mms
		// String phone = Preferences.getPhoneNumber(this);
		// if (phone != null) {
		// i.putExtra("address", phone);
		// }
		i.putExtra("exit_on_sent", true);
		i.putExtra("sms_body", body);
		//
		// etalk
		// i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra("instant.mail.extra.uri", uri.getPath());
		i.putExtra("instant.mail.extra.subject", subject);

		return i;
	}
	
	public static String createName() {
		long date = System.currentTimeMillis();
		return DateFormat.format("yyyy-MM-dd_kkmmss", date).toString();
	}
	
	public static boolean isEZBoardingAvailable(Context ctx) {
		final PackageManager pm = ctx.getPackageManager();
		final Intent i = createEZBoardingIntent();
		List<ResolveInfo> l = pm.queryIntentActivities(i,
				PackageManager.MATCH_DEFAULT_ONLY);
		return (l.size() > 0);
	}
	
	public static Intent createEZBoardingIntent() {
		final Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		i.setClassName("info.niwota.ezb", "info.niwota.ezb.ImageHolderActivity");
		return i;
	}
	
	public static void showDownloadPasta(final Context ctx) {
		final CharSequence title = "Pasta by Li, Qiang";
		final CharSequence msg = "Pasta (free) - Pick and paste frequently used text. Download Pasta from Android Market?";
		final CharSequence yes = "Yes";
		final CharSequence no = "No";
		//
		AlertDialog d = new AlertDialog.Builder(ctx).create();
		d.setIcon(android.R.drawable.ic_dialog_info);
		d.setTitle(title);
		d.setMessage(msg);
		d.setButton(yes, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					Uri uri = Uri.parse(INSTALL_PASTA_PKG);
					Intent i = new Intent(Intent.ACTION_VIEW, uri);
					ctx.startActivity(i);
				} catch (Exception e) {
					Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_SHORT);
				}
				dialog.dismiss();
				return;
			}
		});
		d.setButton2(no, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(ctx, "Download cancelled", Toast.LENGTH_SHORT);
				dialog.dismiss();
				return;
			}
		});
		d.show();
	}
	
	public static Intent createPastaIntent() {
		final Intent i = new Intent();
		i.setClassName("info.niwota.pasta", "info.niwota.pasta.PastaActivity");
		return i;
	}
	
	public static File findUniqueFile(File file) {
		if (!file.exists()) {
			return file;
		}
		String dir = file.getParent();
		String name = file.getName();
		String ext = "";
		//
		int idx = name.lastIndexOf(".");
		if (idx > 0) {
			ext = name.substring(idx); //including dot
			name = name.substring(0, idx);
		}
		// Try until we find a filename which
		// does not exist yet.
		for (int i = 0; i < Integer.MAX_VALUE; i++) {
			File candidate = new File(dir, name + "-" + i + ext);
			boolean exists = candidate.exists();
			if (!exists) {
				return candidate;
			}
		}	
		return null;
	}

	public static String truncate(String s, int max) {
		if (s == null) {
			return s;
		}
		int len = s.length();
		return (len > max ? s.substring(0, max) : s);
	}
	
	/**
	 * Create a meaningful name using title and url
	 * 
	 * @param url
	 * @return
	 */
	public static String createName(String url) {
		if (TextUtils.isEmpty(url)) {
			return null;
		}
		Uri u = Uri.parse(url);
		//if path length is less than 2, it is not very meaningful, use host name instead
		//2 (/XX) is arbitrary but should be sufficient
		String pn = getName(u.getPath(), 2);
		if (pn != null) {
			return normalizeName(pn);
		}
		String h = u.getHost();
		if (!TextUtils.isEmpty(h)) {
			//remove last part of domain, .com etc
			int idx = h.lastIndexOf(".");
			return (idx > 0 ? h.substring(0, idx) : h);
		}
		return null;
	}
	
	private static String getName(String p, int min) {
		if (p == null) {
			return null;
		}
		int len = p.length();
		if (len < min) {
			return null;
		}
		int start = (p.endsWith("/") ? len - 2 : len - 1);
		int idx = p.lastIndexOf("/", start);
		p = (idx ==  -1 ? p : p.substring(idx + 1, start + 1));
		return (p.length() < min ? null : p);
	}
}
